package com.hyperf.core.validation.constraintvalidators;

import cn.hutool.core.util.StrUtil;
import com.hyperf.core.validation.constraints.Phone;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 手机号验证的实现类
 *
 * @author lizhaoyang
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {

    private boolean required;

    private Pattern pattern = Pattern.compile("1[23456789]\\d{9}");

    @Override
    public void initialize(Phone constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (!required && StrUtil.isEmpty(s)) {
            return true;
        } else {
            return pattern.matcher(s).matches();
        }
    }
}
